/**
 * @author: zouye<yzyngz@foxmail.com>
 * @date: 2021-09-26 21:09:33
 * @copyright: zouye<yzyngz@foxmail.com>
 */
package com.yeah.spring.springbootstudy.common.aop;

import java.io.BufferedReader;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.yeah.spring.springbootstudy.common.ServletHolder;

/**
 * 实现审计日志 AOP 切面
 */
@Component
@Aspect
public class AuditLogAspect {
	
	@Pointcut("@annotation(com.yeah.spring.springbootstudy.common.aop.AuditLog)")
	public void audit() {}

	@Around("audit()")
	public Object aroundAudit(ProceedingJoinPoint point) {
		
		HttpServletRequest request = ServletHolder.getServletRequest();
		
		// 拼接在 URL 后面的那部分 querystring 内容
		System.out.println("Parameter list:");
		Enumeration<String> names = request.getParameterNames();
		while(names.hasMoreElements()) {
			String name = names.nextElement();
			System.out.println(name + ": " + request.getParameter(name));
		}
		
		// 请求头
		System.out.println("Header list:");
		names = request.getHeaderNames();
		while(names.hasMoreElements()) {
			String name = names.nextElement();
			System.out.println(name + ": " + request.getHeader(name));
		}
		
		
		
		Object result = null;
		try {
			BufferedReader reader = request.getReader();
			char[] buff = new char[1024];
			int size = -1;
			StringBuffer stringBuffer = new StringBuffer();
			while((size = reader.read(buff)) != -1) {
				stringBuffer.append(buff);
			}
			
			System.out.println("String from request: " + stringBuffer.toString());
			
			result = point.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		
		return result;
	}
}
